<?php

/**
 * SigmaCMS - Content Management System
 *
 * Copyright (C) 2008 Pavol Biely
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package    SigmaCMS
 * @author     Pavol Biely <pavolbiely@gmail.com>
 * @copyright  2008 Pavol Biely
 * @license    http://www.gnu.org/licenses/gpl.txt   GNU General Public License
 * @link       http://pabi3.com/
 * @since      0.1.0
 */

final class Admin_Templates
{
	/**
	 * Array, which holds information about template
	 *
	 * @var array
	 */
	private $templates = array();

	/**
	 * Add new template to form for its editing
	 *
	 * @param string $templateId
	 * @param string $pluginId
	 * @param string $description
	 * @return void
	 */
	public function addTemplate($templateId, $pluginId, $description)
	{
		if (Plugin::isInstalled($pluginId)) {
			$sql = db::query("SELECT `id`,`content`,`keywords` FROM ".db::prefix('templates')." WHERE `template_id`='".db::escape($templateId)."' AND `plugin_id`='".db::escape($pluginId)."' LIMIT 1");
			$row = db::fetchObject($sql);
			if (db::numRows($sql) == 1) {
				$index = count($this->templates)+1;
				$this->templates[$index]['id']          = $row->id;
				$this->templates[$index]['content']     = $row->content;
				$this->templates[$index]['keywords']    = $row->keywords;
				$this->templates[$index]['description'] = _hsc($description);
			}
			db::free($sql);
		}
	}

	/**
	 * Add title for templates in form
	 *
	 * @param string $title
	 * @return void
	 */
	public function addTitle($title)
	{
		$key = count($this->templates)+1;
		$this->templates[$key]['title'] = $title;
	}

	/**
	 * Show form for editing templates
	 *
	 * @param string $redirect
	 * @return void
	 */
	public function buildForm($redirect = 'index.php')
	{
		// only privileged members can access this content
		if (!Member::hasAccess('template')) {
			return;
		}

		// if there are no templates, nothing will be displayed
		if (count($this->templates) == 0) return;

		if (isset($_POST['submit-template'])) {
			$template = _post('template');
			foreach ($template as $id => $value) {
				// template content
				$content = $template[$id];

				// update previous template in database
				db::query("UPDATE ".db::prefix('templates')." SET `content`='".db::escape($content)."' WHERE `id`='".intval($id)."'");
			}

			Admin::redirect($redirect);
		}

		echo "<form action='".cfg::URL.cfg::DIR_ADMIN."index.php?"._hsc(_server('QUERY_STRING'))."' method='post'>\n";
		echo "<fieldset>\n";

		for ($i = 1; $i <= count($this->templates); $i++) {
			// display title, if it is possible
			if (isset($this->templates[$i]['title'])) {
				echo "<h3>"._hsc($this->templates[$i]['title'])."</h3>\n";
			}
		
			// continue to next loop, if template ID is not set
			if (!isset($this->templates[$i]['id'])) continue;
		
			// XHTML ID for template
			$id = 'template-'.$this->templates[$i]['id'];
		
			echo "<p>\n";
			echo "<label for='$id'>"._hsc($this->templates[$i]['description'])."</label>\n";

			echo "<div class='right'>\n";
			if (strlen($this->templates[$i]['content']) == 0) {
				$hide = " style='display:none;'";
				echo "<input class='template' onclick='addTemplateContent(\"$id\")' type='button' value='"._ADMIN_TEMPLATES_ADD_CONTENT."' id='$id-link' />\n";
			} else {
				$hide = NULL;
			}
			echo "<input class='template' onclick='addTemplateRow(\"$id\",3)' type='button' value='"._ADMIN_TEMPLATES_ADD_ROW."' />\n";
			echo "<input class='template' onclick='addTemplateRow(\"$id\",-3)' type='button' value='"._ADMIN_TEMPLATES_REMOVE_ROW."' />\n";
			echo "</div>\n";
		
			// set appropriate size of element <textarea> regarding to size of its content
			$rows = count(explode("\n",$this->templates[$i]['content']));
			if ($rows <  5) {
				$rows =  5;
			} else if ($rows > 20) {
				$rows = 20;
			} else {
				$rows += 5;
			}

			Admin::addEvent('preTemplateTextarea',$id,'template['.$this->templates[$i]['id'].']',$this->templates[$i]['content']);

			// text field
			echo "<textarea id='$id' name='template[".$this->templates[$i]['id']."]' rows='$rows' cols='50'$hide>"._hsc($this->templates[$i]['content'])."</textarea>\n";

			Admin::addEvent('posTemplateTextarea',$id,'template['.$this->templates[$i]['id'].']',$this->templates[$i]['content']);

			// available keywords in template
			$keywords = $this->templates[$i]['keywords'];

			// are there any keywords available?
			if(strlen($keywords) > 0) {
				// split keywords
				$keywords = explode(',',$keywords);

				// remove unnecessary characters
				array_walk($keywords,'_hsc');

				// display keywords if, it is possible
				if (count($keywords) > 0) {
					echo "<br />\n<strong>"._ADMIN_TEMPLATES_KEYWORDS."</strong>\n";
					echo "<br />\n&lt;%template( \n";
					for ($j = 0; $j < count($keywords); $j++) {
						if($j > 0) echo " , ";
						echo "<a href='javascript:addValue(\"$id\",\"&lt;%template({$keywords[$j]})%&gt;\")'>".$keywords[$j]."</a>\n";
					}
					echo " )%&gt;\n";
				}
			}

			echo "</p>\n";
			echo "<hr />\n";
		}
		
		echo "<p class='center'>\n";
		echo "<input name='submit-template' type='submit' value='"._ADMIN_EDIT."' />\n";
		echo "</p>\n";
		
		echo "</fieldset>\n";
		echo "</form>\n";
	}

	/**
	 * Create a new template for plugin
	 *
	 * @param string $templateId
	 * @param string $pluginId
	 * @param string $content
	 * @return boolean
	 */
	public function insertNewTemplate($templateId, $pluginId, $content = NULL, $keywords = NULL)
	{
		// insert new template to database
		$sql = db::query(
		"INSERT INTO ".db::prefix('templates')."(`template_id`,`plugin_id`,`content`,`keywords`)"
		."VALUES("
		."'".db::escape($templateId)."',"
		."'".db::escape($pluginId)."',"
		."'".db::escape($content)."',"
		."'".db::escape($keywords)."'"
		.")"
		);
		
		if ($sql) {
			return true;
		}
		
		return false;
	}

	/**
	 * Delete an old template
	 *
	 * @param string $templateId
	 * @param string $pluginId
	 * @return boolean
	 */
	public function deleteOldTemplate($templateId, $pluginId)
	{
		// delete all templates (*) or just one?
		if ($templateId == '*') {
			$sql = db::query("DELETE FROM ".db::prefix('templates')." WHERE `plugin_id`='".db::escape($pluginId)."'");
		} else {
			$sql = db::query("DELETE FROM ".db::prefix('templates')." WHERE `template_id`='".db::escape($templateId)."' AND `plugin_id`='".db::escape($pluginId)."' LIMIT 1");
		}

		if ($sql) {
			return true;
		}

		return false;
	}
}
